
var api = require('../../utils/api.js');
var app = getApp();
Page({
    data: {
        tophe:0,
        photo:''
    },
    currentPageNumber: 1,
    onLoad(ret) {
       this.getallphoto(ret.id);
    },

    back(){
        wx.navigateBack();
    },
    onShow() {
        let jn = wx.getMenuButtonBoundingClientRect();

        console.log(jn);
        var tophe=jn.top+jn.height+75;
        this.setData({
            tophe:tophe+'px',
            over:jn.top
        })
     
    },

    // 判断文件是否为视频
    isVideoFile(url) {
        const videoExtensions = ['.mp4', '.mov', '.avi', '.wmv', '.flv', '.mkv', '.m4v', '.3gp'];
        const lowerUrl = url.toLowerCase();
        return videoExtensions.some(ext => lowerUrl.endsWith(ext));
    },
    
    getallphoto(id){
        var that=this;
        api.post({
            url: 'photo/getphotobyid',
            data: {id:id},
            success: data => {
                // 为每个文件添加类型标识
                if (data.data.images && data.data.images.length > 0) {
                    data.data.images.forEach(item => {
                        item.isVideo = that.isVideoFile(item.img);
                    });
                }
                
                that.setData({
                    photo: data.data,
                    images: data.data.images
                });
            },
        });
    },
    getme(ret){
        console.log(ret);
        var i=ret.currentTarget.dataset.i;
        var images=this.data.images;
        var s=images[i].s;

        if(s==1){
            s=0;
        }else{
            s=1;
        }

        images[i].s=s;

        this.setData({
            images:images
        })


    },

    //下载文件到手机
    downfile(){
        const that = this;
        const images = this.data.images;
        const selectedImages = images.filter(item => item.s === 1);
        
        if (selectedImages.length === 0) {
            wx.showToast({
                title: '请先选择文件',
                icon: 'none',
                duration: 2000
            });
            return;
        }
        
        wx.showLoading({
            title: '正在下载...',
            mask: true
        });
        
        let successCount = 0;
        let failCount = 0;
        let totalCount = selectedImages.length;
        
        // 判断文件类型
        function isVideoFile(url) {
            const videoExtensions = ['.mp4', '.mov', '.avi', '.wmv', '.flv', '.mkv', '.m4v', '.3gp'];
            const lowerUrl = url.toLowerCase();
            return videoExtensions.some(ext => lowerUrl.endsWith(ext));
        }
        
        // 递归下载文件
        function downloadFile(index) {
            if (index >= selectedImages.length) {
                wx.hideLoading();
                wx.showToast({
                    title: `下载完成，成功${successCount}个，失败${failCount}个`,
                    icon: 'none',
                    duration: 3000
                });
                return;
            }
            
            const fileUrl = selectedImages[index].img;
            const isVideo = isVideoFile(fileUrl);
            
            // 先下载文件
            wx.downloadFile({
                url: fileUrl,
                success: function(res) {
                    if (res.statusCode === 200) {
                        if (isVideo) {
                            // 保存视频到相册
                            wx.saveVideoToPhotosAlbum({
                                filePath: res.tempFilePath,
                                success: function() {
                                    successCount++;
                                    downloadFile(index + 1);
                                },
                                fail: function(err) {
                                    console.error('保存视频失败', err);
                                    failCount++;
                                    downloadFile(index + 1);
                                }
                            });
                        } else {
                            // 保存图片到相册
                            wx.saveImageToPhotosAlbum({
                                filePath: res.tempFilePath,
                                success: function() {
                                    successCount++;
                                    downloadFile(index + 1);
                                },
                                fail: function(err) {
                                    console.error('保存图片失败', err);
                                    failCount++;
                                    downloadFile(index + 1);
                                }
                            });
                        }
                    } else {
                        console.error('下载文件失败', res);
                        failCount++;
                        downloadFile(index + 1);
                    }
                },
                fail: function(err) {
                    console.error('下载文件失败', err);
                    failCount++;
                    downloadFile(index + 1);
                }
            });
        }
        
        // 请求相册权限
        wx.getSetting({
            success: res => {
                // 检查是否有保存到相册的权限
                if (!res.authSetting['scope.writePhotosAlbum']) {
                    wx.authorize({
                        scope: 'scope.writePhotosAlbum',
                        success: () => {
                            // 开始下载第一个文件
                            downloadFile(0);
                        },
                        fail: () => {
                            wx.hideLoading();
                            wx.showModal({
                                title: '提示',
                                content: '需要您授权保存到相册',
                                confirmText: '去授权',
                                success: modalRes => {
                                    if (modalRes.confirm) {
                                        wx.openSetting({
                                            success: settingRes => {
                                                if (settingRes.authSetting['scope.writePhotosAlbum']) {
                                                    // 获得授权后开始下载
                                                    downloadFile(0);
                                                } else {
                                                    wx.showToast({
                                                        title: '授权失败，无法下载到相册',
                                                        icon: 'none',
                                                        duration: 2000
                                                    });
                                                }
                                            }
                                        });
                                    } else {
                                        wx.showToast({
                                            title: '授权失败，无法下载到相册',
                                            icon: 'none',
                                            duration: 2000
                                        });
                                    }
                                }
                            });
                        }
                    });
                } else {
                    // 已有权限，直接开始下载
                    downloadFile(0);
                }
            }
        });
    },

    seeimgage(ret){
        console.log(ret);
        var img=ret.currentTarget.dataset.img;
        wx.previewImage({
            current: img, // 当前显示图片的http链接
            urls: [img] // 需要预览的图片http链接列表
          })
    },

    seevideo(ret){
        console.log(ret);
        var img=ret.currentTarget.dataset.img;
        var list=[{url:img,type:'video'}];


        wx.previewMedia({
            sources:list,
            current:0
        })
    }

});